package cn.com.yiqi.wsc.portal.controller.order;

import cn.com.yiqi.wsc.Ro.CustomerRo;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.dao.customer.criteria.CustomerListCriteria;
import cn.com.yiqi.wsc.dao.order.criteria.OrderCriteria;
import cn.com.yiqi.wsc.dao.order.criteria.OrderRefundCriteria;
import cn.com.yiqi.wsc.entity.order.OrderLogistics;
import cn.com.yiqi.wsc.entity.order.OrderMainDTO;
import cn.com.yiqi.wsc.entity.order.OrderRefund;
import cn.com.yiqi.wsc.entity.order.OrderRefundLog;
import cn.com.yiqi.wsc.entity.user.User;
import cn.com.yiqi.wsc.enumeration.UserType;
import cn.com.yiqi.wsc.portal.controller.BaseController;
import cn.com.yiqi.wsc.service.order.PortalOrderService;
import cn.com.yiqi.wsc.service.order.enumeration.OrderRefundStatus;
import cn.com.yiqi.wsc.service.outputExcel.OutPutService;
import cn.com.yiqi.wsc.service.user.UserService;
import cn.com.yiqi.wsc.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by 苟宇恒 on 2017/2/22.
 * 订单管理
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {


    @Autowired
    private PortalOrderService portalOrderService;
    @Autowired
    private OutPutService outPutService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("order/index");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/detail")
    public ModelAndView detail(@RequestParam("orderId") Integer orderId) {
        ModelAndView mv = new ModelAndView("order/detail");

        OrderCriteria criteria = new OrderCriteria();
        criteria.setId(orderId);
        Map<String, Object> orderData = portalOrderService.detail(criteria).getData();
        if (null != orderData) {
            mv.addObject("detail", JsonUtil.toJSON(orderData.get("detail")));
            mv.addObject("orderList", JsonUtil.toJSON(orderData.get("orderList")));
        }
        mv.addObject("payDetail", JsonUtil.toJSON(portalOrderService.payDetail(criteria).getData().get("payDetail")));
        mv.addObject("shipLogisticsDetail", JsonUtil.toJSON(portalOrderService.shipLogisticsDetail(criteria).getData().get("shipLogisticsDetail")));
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/item/index")
    public ModelAndView item() {
        ModelAndView mv = new ModelAndView("order/item/index");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/item/detail")
    public ModelAndView itemDetail(@RequestParam("orderId") Integer orderId) {
        ModelAndView mv = new ModelAndView("order/item/detail");

        OrderCriteria criteria = new OrderCriteria();
        criteria.setId(orderId);

        mv.addObject("detail", JsonUtil.toJSON(portalOrderService.detail(criteria).getData().get("detail")));
        mv.addObject("shipLogisticsDetail", JsonUtil.toJSON(portalOrderService.shipLogisticsDetail(criteria).getData().get("shipLogisticsDetail")));


        mv.addObject("itemList", JsonUtil.toJSON(portalOrderService.orderItems(orderId.longValue()).getReturnValue()));
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/sysItemDetail")
    public ModelAndView sysItemDetail(@RequestParam("orderId") Integer orderId) {
        ModelAndView mv = new ModelAndView("order/sysItemDetail");

        OrderCriteria criteria = new OrderCriteria();
        criteria.setId(orderId);

        mv.addObject("detail", JsonUtil.toJSON(portalOrderService.detail(criteria).getData().get("detail")));
        mv.addObject("shipLogisticsDetail", JsonUtil.toJSON(portalOrderService.shipLogisticsDetail(criteria).getData().get("shipLogisticsDetail")));


        mv.addObject("itemList", JsonUtil.toJSON(portalOrderService.orderItems(orderId.longValue()).getReturnValue()));
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/item/orderItemInfo")
    @ResponseBody
    public Result orderItemInfo(@RequestParam("orderId") Integer orderId) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        OrderCriteria criteria = new OrderCriteria();
        criteria.setId(orderId);
        Result detail = portalOrderService.detail(criteria);
        if (detail.getStatus() == 200) {
            result.putData("detail", detail.getData().get("detail"));
        }
        Result ship = portalOrderService.shipLogisticsDetail(criteria);
        if (ship.getStatus() == 200) {
            result.putData("shipLogisticsDetail", ship.getData().get("shipLogisticsDetail"));
        }
        Result itemList = portalOrderService.orderItems(orderId.longValue());
        if (itemList.getStatus() == 100) {
            result.putData("itemList", itemList.getReturnValue());
        }
        return result;
    }

    @RequestMapping(value = "/list0", method = RequestMethod.POST)
    @ResponseBody
    public Result pageList0(@RequestBody OrderCriteria criteria) {
        Result result = new Result();

        criteria.setPid(0);

//        User currentUser = userService.getCurrentUser();
//        Integer userType = currentUser.getType();
//
//        if (UserType.seller.getValue()==userType) {
//            //如果是商家
//            criteria.setOrgId(currentUser.getOrgId());
//        } else {
//            criteria.setPid(0);
//        }

        result = portalOrderService.pageList(criteria);

        return result;
    }

    @RequestMapping(value = "/list1", method = RequestMethod.POST)
    @ResponseBody
    public Result pageList1(@RequestBody OrderCriteria criteria) {
        Result result = new Result();

        User currentUser = userService.getCurrentUser();
//        Integer userType = currentUser.getType();
        criteria.setOrgId(currentUser.getOrgId());
//        if (UserType.seller.getValue()==userType) {
//            //如果是商家
//
//        } else {
//            criteria.setPid(0);
//        }

        result = portalOrderService.pageList(criteria);

        return result;
    }

    @RequestMapping("/logistics/add")
    @ResponseBody
    public Result addLogistics(@RequestBody OrderLogistics orderLogistics) {

        Result result = new Result();

        result = portalOrderService.insertLogistics(orderLogistics);

        return result;
    }


    @RequestMapping("/refund/list")
    @ResponseBody
    public Result refundPageList(@RequestBody OrderRefundCriteria criteria) {

        Result result = new Result();
        if (null == criteria.getStatus()) {
            criteria.setStatusList(Arrays.asList(new Integer[]{
                    OrderRefundStatus.org_check.getValue(),
                    OrderRefundStatus.finance_check.getValue(),
                    OrderRefundStatus.operator_check.getValue(),
                    OrderRefundStatus.confirm_refund.getValue()
            }));
        }
        criteria.setOrderBy("mor.n_status desc");
        User currentUser = userService.getCurrentUser();
        Integer userType = currentUser.getType();
        if (UserType.seller.getValue() == userType) {
            //如果是商家
            criteria.setOrgId(currentUser.getOrgId().longValue());
        }
        result = portalOrderService.refundPageList(criteria);

        return result;
    }

    @RequestMapping("/refund/finishedList")
    @ResponseBody
    public Result refundFinishedList(@RequestBody OrderRefundCriteria criteria) {

        Result result = new Result();
        if (null == criteria.getStatus()) {
            criteria.setStatusList(Arrays.asList(new Integer[]{
                    OrderRefundStatus.reject.getValue(),
                    OrderRefundStatus.completed.getValue()
            }));
        }
        User user = userService.getCurrentUser();
        if(UserType.seller.getValue() == user.getType()){
            criteria.setOrgId(user.getOrgId().longValue());
        }
        criteria.setOrderBy("mor.d_complete_time desc");
        result = portalOrderService.refundPageList(criteria);

        return result;
    }


    @RequestMapping("/refund/check/org")
    @ResponseBody
    public Result refundCheckOrg(@RequestBody OrderRefundLog orderRefundLog) {

        Result result = new Result();

        result = portalOrderService.refundCheckOrg(orderRefundLog);

        return result;
    }


    @RequestMapping("/refund/check/finance")
    @ResponseBody
    public Result refundCheckFinance(@RequestBody OrderRefundLog orderRefundLog) {

        Result result = new Result();

        result = portalOrderService.refundCheckFinance(orderRefundLog);

        return result;
    }

    @RequestMapping("/refund/check/operator")
    @ResponseBody
    public Result refundCheckOperator(@RequestBody OrderRefundLog orderRefundLog) {

        Result result = new Result();


        result = portalOrderService.refundCheckOperator(orderRefundLog);

        return result;
    }

    @RequestMapping("/refund/confirm")
    @ResponseBody
    public Result refundCheckConfirm(@RequestBody OrderRefund orderRefund) {

        Result result = new Result();


        User user = userService.getCurrentUser();

        OrderRefund orderRefundForUpdate = new OrderRefund();
        orderRefundForUpdate.setId(orderRefund.getId());
        orderRefundForUpdate.setStatus(OrderRefundStatus.confirm_refund.getValue());
        orderRefundForUpdate.setUpdateUserId(user.getUpdateUserId());

        result = portalOrderService.refundConfirm(orderRefund);

        return result;
    }

    @RequestMapping("/refund/logList")
    @ResponseBody
    public Result refundLogList(HttpServletRequest request) {

        Result result = new Result();

        String refundId = request.getParameter("refundId");
        if (StringUtils.isEmpty(refundId)) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            return result;
        }
        result = portalOrderService.refundLogList(Long.parseLong(refundId));

        return result;
    }

    @RequestMapping("/outPut")
    public void outPut(@RequestBody OrderCriteria criteria, HttpServletRequest request, HttpServletResponse response) {
        criteria.setPageSize(500000);
        List<OrderMainDTO> list = (List<OrderMainDTO>) portalOrderService.pageList(criteria).getData().get("list");
        String title = "订单管理-平台";
        String[] hearders = new String[]{"订单号", "客户编号", "客户姓名", "订单状态", "下单时间", "付款完成时间", "实付款(￥)"};//表头数组
        String[] fields = new String[]{"orderCode", "customerCode", "customerName", "statusName", "createTime", "payTime", "amount"};//People对象属性数组
        String creater = userService.getCurrentUser().getRealName();
        try {
            outPutService.outPutExcel(list, title, hearders, fields, creater, request, response);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    @RequestMapping("/outPutOneLevelOrg")
    public void outPutOneLevelOrg(@RequestBody OrderCriteria criteria, HttpServletRequest request, HttpServletResponse response) {
        criteria.setPageSize(500000);
        criteria.setPid(0);
        List<OrderMainDTO> list = (List<OrderMainDTO>) portalOrderService.pageList(criteria).getData().get("list");
        String title = "订单管理-商家";
        String[] hearders = new String[]{"订单号", "客户姓名", "实付款(￥)", "订单状态", "下单时间", "付款完成时间"};//表头数组
        String[] fields = new String[]{"orderCode", "customerName", "amount", "statusName", "createTime", "payTime"};//People对象属性数组
        String creater = userService.getCurrentUser().getRealName();
        try {
            outPutService.outPutExcel(list, title, hearders, fields, creater, request, response);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    @RequestMapping("/notify/org")
    @ResponseBody
    public Result notifyOrg(@RequestBody OrderCriteria criteria) {


        Integer orderId = criteria.getId();

        Result result = new Result();
        if (orderId == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            return result;
        }

        result = portalOrderService.notifyOrg(orderId);

        return result;


    }
}
